package com.android.settings.audio.peq.peq.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.settings.R;
import com.android.settings.audio.peq.util.GetSize;
import com.android.settings.audio.peq.util.SmartPlayerApplication;
import com.android.settings.audio.peq.util.Util;

import java.util.ArrayList;

public class CommanDialog extends Dialog {
    private Context mContext;
    private LinearLayout mViewGroup_Container;
    public TextView ok, cancle, more, titleTextView, mTv_Content;
    private Handler handler = new Handler();
    public View mView_Content;
    private int itemCount = -1;
    private boolean isAutoHeight = false;
    public View buttonContainerView;
    public static final int STYLE_NOTITLE_NOBUTTON = 99;
    public static final int STYLE_POP_NOBUTTON = 98;
    public static final int STYLE_POP_NOTITLE_NOBUTTON = 97;
    public static final int STYLE_3_HASTITLE_HASTWOBUTTON = 96;
    public static final int STYLE_3_HASTITLE_NOBUTTON = 95;
    public static final int STYLE_3_HASTITLE_ONEBUTTON = 94;
    public static final int STYLE_4_HASTITLE_ONEBUTTON = 93;
    public static final int STYLE_3_HASTITLE_THREEBUTTON = 92;
    public static final int STYLE_3_HASTITLE_TWOBUTTON_CONTENT = 91;

    private onCancelDialogListener cancelDialogListener;
    private OnDialogShowListener mOnDialogShowListener;
    private ViewTreeObserver.OnWindowFocusChangeListener mOnWindowFocusChangeListener;
    private OnDismissListener onDismissListener;

    public CommanDialog(Context context) {
        super(context);

        mContext = context;
        initUI();
    }

    public CommanDialog(Context context, boolean isone) {

        super(context);
        mContext = context;
        initUI_oneButton();
    }


    public CommanDialog(Context context, int mydialogstyle) {

        super(context, mydialogstyle);
        mContext = context;
        initUI();
    }

    public CommanDialog(Context context, int mydialogstyle, int Style) {

        super(context, mydialogstyle);
        mContext = context;
        if (Style == 100) {
            initUI_changeableSize_oneButton();
        } else if (Style == STYLE_POP_NOBUTTON) {
            initUI3_Pop_noButton();
        } else if (Style == STYLE_NOTITLE_NOBUTTON) {
            initUI_noTitle_noButton();
        } else if (Style == STYLE_POP_NOTITLE_NOBUTTON) {
            initUI_Pop_NoTitle_NoButton();
        } else if (Style == STYLE_3_HASTITLE_HASTWOBUTTON) {
            initUI3_HasTitle_HasTwoButton();
        } else if (Style == STYLE_3_HASTITLE_NOBUTTON) {
            initUI_Pop_HasTitle_NoButton();
        } else if (Style == STYLE_3_HASTITLE_ONEBUTTON) {
            initUI3_HasTitle_HasOneButton();
        } else if (Style == STYLE_4_HASTITLE_ONEBUTTON) {
            initUI4_HasTitle_HasOneButton();
        } else if (Style == STYLE_3_HASTITLE_THREEBUTTON) {
            initUI3_HasTitle_ThreeButton();
        } else if (Style == STYLE_3_HASTITLE_TWOBUTTON_CONTENT) {
            initUI3_HasTitle_HasTwoButton_ContentTV();
        } else {
            initUI_oneButton();
        }
    }

    public CommanDialog(Context context, int mydialogstyle, boolean flag) {

        super(context, mydialogstyle);
        mContext = context;
        if (flag) {
            initUI_noButton();
        } else {
            initUI_changeableSize_noButton();
        }
    }

    public void setItemCount(int i) {

        itemCount = i;
    }

    public void setAutoHeight(boolean auto) {
        isAutoHeight = auto;
    }

    public void addView(int id) {
        if (mContext != null) {
            LayoutInflater layoutInflater = LayoutInflater.from(mContext);
            mView_Content = layoutInflater.inflate(id, null);

            adjust_view_size(mViewGroup_Container);
        }
    }

    public void addBottomView(int id) {
        if (mContext != null) {
            addViewWithAnimaition(id, Gravity.BOTTOM);
            adjust_view_size(mViewGroup_Container);
        }
    }

    public void addBottomViewNoAdjustView(int id) {
        if (mContext != null) {
            addViewWithAnimaition(id, Gravity.BOTTOM);
            mViewGroup_Container.addView(mView_Content);
        }
    }

    public void addViewWithAnimaition(int id, int gravity) {
        if (mContext != null) {
            Window window = getWindow();
            if (gravity != -1) {
                window.setGravity(gravity);
            }
            window.setLayout(GetSize.getscreenWidth(mContext), this.getWindow().getAttributes().height);
            LayoutInflater layoutInflater = LayoutInflater.from(mContext);
            mView_Content = layoutInflater.inflate(id, null);
            addAnimation(mViewGroup_Container);
        }
    }

    private void addAnimation(final View mView) {
        Window window = getWindow(); // 得到对话框
        window.setWindowAnimations(R.style.peqbottomTotop); // 设置窗口弹出动画

    }

    private void adjust_view_size(final View mView) {

        final ViewTreeObserver vto = mView.getViewTreeObserver();

        vto.addOnPreDrawListener(new OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                mView.getViewTreeObserver().removeOnPreDrawListener(this);

                handler.post(new Runnable() {

                    @Override
                    public void run() {

                        LayoutParams layoutParams = mView.getLayoutParams();
                        // int DialogHeiht=0;
                        // if(getContentView()!=null)
                        // DialogHeiht=getContentView().getHeight();
                        if (isAutoHeight) {
                            if ((getHeight((Activity) mContext) / GetSize.dip2px(mContext, 46)) <= itemCount) {
                                layoutParams.height = getHeight((Activity) mContext);
                                mView.setLayoutParams(layoutParams);
                            }
                        } else {
                            if (itemCount > 5) {
                                layoutParams.height = GetSize.dip2px(mContext, 234);
                                mView.setLayoutParams(layoutParams);
                            }
                        }
                        if (mView_Content != null)
                            ((ViewGroup) mView).addView(mView_Content);

                    }
                });
                return true;
            }
        });
    }

    private static final String TAG = "CommanDialog";

    public int getHeight(Activity activity) {
        WindowManager manage = activity.getWindowManager();
        Display display = manage.getDefaultDisplay();
        return (display.getHeight() - GetSize.dip2px(mContext, 160));
    }

    public void addView(View view) {

        mViewGroup_Container.addView(view);
        adjust_view_size(mViewGroup_Container);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (mOnWindowFocusChangeListener != null)
            mOnWindowFocusChangeListener.onWindowFocusChanged(hasFocus);
    }

    @Override
    public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
        super.onWindowAttributesChanged(params);

    }

    @Override
    public void show() {
        if (mContext == null) return;
        if (mContext instanceof Activity && (((Activity) mContext).isFinishing() || ((Activity) mContext).isDestroyed())) {
            return;
        }
        if (mOnDialogShowListener != null) {
            mOnDialogShowListener.onDialogShow();
        }
        SmartPlayerApplication.getMainHandler().removeCallbacks(showRunnable);
        SmartPlayerApplication.getMainHandler().postDelayed(showRunnable, 0);

        initClickTitleToClose();
    }

    public void show(long delayMillis) {
        if (mContext == null) return;
        if (mContext instanceof Activity && (((Activity) mContext).isFinishing() || ((Activity) mContext).isDestroyed())) {
            return;
        }
        if (mOnDialogShowListener != null) {
            mOnDialogShowListener.onDialogShow();
        }
        SmartPlayerApplication.getMainHandler().removeCallbacks(showRunnable);
        SmartPlayerApplication.getMainHandler().postDelayed(showRunnable, delayMillis);

        initClickTitleToClose();
    }

    private void initClickTitleToClose() {
        if (mContext == null) return;
        if (!Util.isTalkbackEnabled(mContext)) {
            return;
        }
        boolean mCancelableOnTouchOutSide = true;//todo
        if (titleTextView != null && mCancelableOnTouchOutSide) {
            titleTextView.setContentDescription(titleTextView.getText() + "," + mContext.getString(R.string.peq_cd_click_to_close_dialog));
            titleTextView.setOnClickListener((v) -> {
                dismiss();
            });
        }
    }

    private Runnable showRunnable = () -> {
        try {
            if (mContext instanceof Activity && (((Activity) mContext).isFinishing() || ((Activity) mContext).isDestroyed())) {
                return;
            }
            SmartPlayerApplication.runOnUiThread(CommanDialog.super::show);
        } catch (Exception e) {
            e.printStackTrace();
        }
    };

    @Override
    public void cancel() {
        super.cancel();

        SmartPlayerApplication.getMainHandler().removeCallbacks(showRunnable);

        if (cancelDialogListener != null) {
            cancelDialogListener.cancelDialog();
        }
    }

    @Override
    public void dismiss() {
        SmartPlayerApplication.getMainHandler().removeCallbacks(showRunnable);

        if (cancelDialogListener != null) {
            cancelDialogListener.cancelDialog();
        }
        if (mContext != null) {
            if (mContext instanceof Activity && (((Activity) mContext).isFinishing() || ((Activity) mContext).isDestroyed())) {
                return;
            }
            try {
                super.dismiss();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    void initUI() {
        setContentView(R.layout.peq_dialog_comman);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.l_ok);
        cancle = (TextView) findViewById(R.id.l_cancle);
        buttonContainerView = findViewById(R.id.container_button);
        if (Util.checkAppIsProductTV()) {
            SetFoucsMove(ok);
            SetFoucsMove(cancle);
        }
    }

    void initUI_oneButton() {
        setContentView(R.layout.peq_dialog_comman2);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.cancle);
        // cancle = (TextView) findViewById(R.id.l_cancle);
        if (Util.checkAppIsProductTV()) {
            SetFoucsMove(ok);
        }

    }

    void initUI_noButton() {
        setContentView(R.layout.peq_dialog_comman3);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
    }

    void initUI_changeableSize_oneButton() {
        setContentView(R.layout.peq_dialog_comman4);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.cancle);
        if (Util.checkAppIsProductTV()) {
            SetFoucsMove(ok);
        }
    }

    void initUI_changeableSize_noButton() {
        setContentView(R.layout.peq_dialog_comman5);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.btn_ensure);
        cancle = (TextView) findViewById(R.id.btn_cancel);
    }

    void initUI_noTitle_noButton() {
        setContentView(R.layout.peq_dialog_comman6);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
    }

    void initUI3_Pop_noButton() {
        setContentView(R.layout.peq_dialog_comman7);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ImageView close_btn = findViewById(R.id.close_btn);
        close_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    void initUI_Pop_NoTitle_NoButton() {
        setContentView(R.layout.peq_dialog_comman6);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
    }

    void initUI_Pop_HasTitle_NoButton() {
        setContentView(R.layout.peq_dialog_comman8);

        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        View container_btn = findViewById(R.id.container_btn);
        container_btn.setVisibility(View.GONE);
        titleTextView = (TextView) findViewById(R.id.title);
    }

    void initUI3_HasTitle_HasTwoButton() {
        setContentView(R.layout.peq_dialog_comman8);
        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.btn_ensure);
        cancle = (TextView) findViewById(R.id.btn_cancel);
        if (Util.checkAppIsProductTV()) {
            SetFoucsMove(ok);
            SetFoucsMove(cancle);
        }
    }

    void initUI3_HasTitle_HasOneButton() {
        setContentView(R.layout.peq_dialog_comman8);
        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.btn_ensure);
        cancle = (TextView) findViewById(R.id.btn_cancel);
        cancle.setVisibility(View.GONE);
        if (Util.checkAppIsProductTV()) {
            SetFoucsMove(ok);
            SetFoucsMove(cancle);
        }
    }

    void initUI4_HasTitle_HasOneButton() {
        if (Util.checkIsUserLandScreenSmallLayout(mContext)) {
            setContentView(R.layout.peq_dialog_comman9_small);
        } else {
            setContentView(R.layout.peq_dialog_comman9);
        }
        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.btn_ensure);
        if (Util.checkAppIsProductTV()) {
            SetFoucsMove(ok);
            SetFoucsMove(mViewGroup_Container);
        }
    }

    void initUI3_HasTitle_ThreeButton() {
        setContentView(R.layout.peq_dialog_comman10);
        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.btn_ensure);
        cancle = (TextView) findViewById(R.id.btn_cancel);
        more = (TextView) findViewById(R.id.btn_ok);
        if (Util.checkAppIsProductTV()) {
            SetFoucsMove(ok);
            SetFoucsMove(cancle);
            SetFoucsMove(more);
//            SetFoucsMove(mViewGroup_Container);
        }
    }

    void initUI3_HasTitle_HasTwoButton_ContentTV() {
        setContentView(R.layout.peq_dialog_comman11);
        mViewGroup_Container = (LinearLayout) findViewById(R.id.contentlayout);
        titleTextView = (TextView) findViewById(R.id.title);
        ok = (TextView) findViewById(R.id.btn_ensure);
        cancle = (TextView) findViewById(R.id.btn_cancel);
        mTv_Content = (TextView) findViewById(R.id.tv_content);
        if (Util.checkAppIsProductTV()) {
            SetFoucsMove(ok);
            SetFoucsMove(cancle);
//           SetFoucsMove(mViewGroup_Container);
        }
    }

    public View getContentView() {

        return mView_Content;
    }

    public void setOnCancelDialogListener(onCancelDialogListener cancelDialogListener) {
        this.cancelDialogListener = cancelDialogListener;
    }

    public void setOnDialogShowListener(OnDialogShowListener listener) {
        this.mOnDialogShowListener = listener;
    }

    public void setOnWindowFocusChangedListener(ViewTreeObserver.OnWindowFocusChangeListener listener) {
        this.mOnWindowFocusChangeListener = listener;
    }

    public interface onCancelDialogListener {
        public void cancelDialog();
    }

    public interface OnDialogShowListener {
        void onDialogShow();
    }

    private void SetFoucsMove(ViewGroup viewGroup) {
        if (viewGroup != null)
            viewGroup.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasfocus) {
                    if (hasfocus) {
                        viewGroup.setBackgroundResource(R.color.peq_skin_background);

                    } else {
                        viewGroup.setBackgroundResource(R.color.peq_skin_dialog_background);
                    }
                }
            });
    }

    private void SetFoucsMove(TextView textView) {
        if (textView != null)
            textView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasfocus) {
                    if (hasfocus) {
//                        textView.setBackgroundResource(R.color.dialog_divide_line_3);
                        textView.setTextColor(Color.argb(255, 23, 169, 203));
                    } else {
                        textView.setTextColor(Color.argb(255, 204, 204, 204));
                    }
                }
            });
    }


    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }


    /********************************************dialog disimss lienter***********************************************/

    private ArrayList<OnDismissListener> listenerlist = new ArrayList<>();

    @Override
    public void setOnDismissListener(@Nullable OnDismissListener listener) {
        if (onDismissListener == null) {
            onDismissListener = new OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    notifyDialogDismiss();
                }
            };
        }
        if (listenerlist.size() == 0) {
            super.setOnDismissListener(onDismissListener);
        }

        listenerlist.add(listener);
    }

    public void removeDismissListener(OnDismissListener listener) {
        if (listenerlist.contains(listener)) {
            listenerlist.remove(listener);
        }
    }

    private void notifyDialogDismiss() {
        for (OnDismissListener listener : listenerlist) {
            listener.onDismiss(this);
        }
    }


}
